<template>
    <el-dialog
        v-model="show"
        append-to-body
        destroy-on-close
        width="815px"
        class="zw-unityKit-material-lib"
        @close="onClose">
        <template #header>
            <div class="dialog-header">素材库选择</div>
        </template>
        <div class="tab_box">
            <div class="tab-header">
                <el-tabs v-model="tabsType" class="base_tabs" @tab-change="onTabs">
                    <el-tab-pane
                        v-for="item in tabs"
                        :key="item.type"
                        :label="item.name"
                        :name="item.type"
                        :disabled="tabsDisabled && tabsType != item.type">
                    </el-tab-pane>
                </el-tabs>
                <div class="tab_reset" @click="onRefresh">刷新</div>
            </div>
            <div class="content-box">
                <div v-if="!noGroupTabTypeList.includes(tabsType)" class="content-box-group">
                    <GroupTree
                        v-model="baseInfo.group_id"
                        :loading="baseInfo.groupLoading"
                        :group-data="groupData"
                        @submit="onGroupTree" />
                </div>
                <div class="content-box-right">
                    <div>
                        <!-- 电商素材类型 -->
                        <ECommerceToggle v-if="isToggleType" v-model="toggleType" :is-goods-only="isGoodsOnly" />
                        <!-- 公众号搜索 -->
                        <SearchOfficial
                            v-if="tabsType == 10"
                            v-model="baseInfo.searchOfficial"
                            @submit="getTableData" />
                        <!-- 小程序搜索 -->
                        <SearchMp v-else-if="tabsType == 11" v-model="baseInfo.searchMp" @submit="getTableData" />
                        <!-- 其他类型搜索 -->
                        <SearchInput v-else v-model="baseInfo.keyword" @submit="getTableData" />
                    </div>
                    <el-scrollbar ref="tableScrollBarRef" v-loading="baseInfo.loading" class="table-box">
                        <template v-for="(item, index) in tabs" :key="index">
                            <component
                                :is="item?.comName"
                                v-if="item.type == tabsType"
                                v-model="item.selectList"
                                :scene-value="props.sceneValue"
                                :data="tableData"
                                :select-total-num="item.total"
                                :remain-num="remainNum" />
                        </template>
                    </el-scrollbar>
                    <div class="pagination-box">
                        <Pagination
                            :page="pageInfo.page"
                            :page-size="pageInfo.page_size"
                            :total="pageInfo.total"
                            @pageChange="pageChange"
                            @sizeChange="pageSizeChange" />
                    </div>
                </div>
            </div>
        </div>
        <!-- 底部 -->
        <template #footer>
            <div class="footer-box">
                <div class="left-desc">
                    <DialogFooter
                        v-if="tabsType != 0"
                        :material-list="selectTabsList"
                        :local-list="selectLocalList"
                        :max-num="9"
                        :remain-num="remainNum"
                        :scene-value="props.sceneValue" />
                </div>
                <div class="right-button">
                    <LocalUploadFile
                        v-if="[1, 2, 4, 5].includes(tabsType)"
                        :type="tabsType"
                        :disabled="uploadDisabled"
                        :scene-value="props.sceneValue"
                        @submit="onLocalUploadFile" />
                    <LocalUploadLink
                        v-else-if="[3].includes(tabsType)"
                        :type="tabsType"
                        :disabled="uploadDisabled"
                        @submit="onLocalUploadFile" />
                    <el-button v-else plain @click="onClose">取消</el-button>
                    <el-button class="ml20" type="primary" @click="onSave"> 保存 </el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ElDialog, ElButton, ElTabs, ElTabPane } from 'element-plus';
import { ref, reactive, shallowRef, watch, computed, withDefaults, getCurrentInstance } from 'vue';
import Pagination from './components/Pagination.vue';
import DialogFooter from './components/DialogFooter.vue';
import GroupTree from './components/GroupTree.vue';
import SearchInput from './components/SearchInput.vue';
import SearchOfficial from './components/SearchOfficial.vue';
import SearchMp from './components/SearchMp.vue';
import ECommerceToggle from './components/ECommerceToggle.vue';
import LocalUploadFile from './components/LocalUploadFile.vue';
import LocalUploadLink from './components/LocalUploadLink.vue';

import TextTable from './table/TextTable.vue';
import ImageTable from './table/ImageTable.vue';
import VideoTable from './table/VideoTable.vue';
import AudioTable from './table/AudioTable.vue';
import LinkTable from './table/LinkTable.vue';
import FileTable from './table/FileTable.vue';
import LuckDrawTable from './table/LuckDrawTable.vue';
import ECommerceTable from './table/ECommerceTable.vue';
import ECommercePageTable from './table/ECommercePageTable.vue';
import CollectTable from './table/CollectTable.vue';
import OfficialAccountTable from './table/OfficialAccountTable.vue';
import MiniAppTable from './table/MiniAppTable.vue';

import {
    groupListApi,
    luckDrawGroupListApi,
    shopGroupListApi,
    textTableApi,
    imageTableApi,
    videoTableApi,
    linkTableApi,
    audioTableApi,
    fileTableApi,
    lotteryTableApi,
    collectTableApi,
    productTableApi,
    pageTableApi,
    officialTableApi,
    miniTableApi
} from '../api/material';

defineOptions({
    name: 'ZwUnityMaterialLib'
});

interface Props {
    /** 弹框是否展示 */
    modelValue?: boolean;
    /** 需要展示tabs */
    showTabsList?: Array<any>;
    /** 素材最大个数 */
    maxNum?: any;
    /** 场景值 */
    sceneValue?: string;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    showTabsList: () => [],
    maxNum: 9,
    sceneValue: ''
});

const emit = defineEmits(['update:modelValue', 'submit']);

const app = getCurrentInstance();

/**
 * 弹框是否展示
 */
const show = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

/**
 * 选中tab页的groupId
 */
const tabsGroupId = computed(() => {
    const info = tabs.value.find(el => el.type == tabsType.value) || {};
    return info.groupId;
});

/**
 * 电商素材-是否展示切换类型
 * 1 客易达  2 有赞  3 淘宝  4 自营  5 线下门店
 */
const isToggleType = computed(() => {
    return tabsType.value == 7 && ['1', '4'].includes(baseInfo.shopType);
});

/**
 * 选中的素材tabs
 */
const selectTabsList = computed(() => {
    return tabs.value.filter((el: any) => el.selectList.length);
});

/**
 * 剩余选择数量
 */
const remainNum = computed(() => {
    let num = 0;
    let residueNum = 0;
    selectTabsList.value.map(el => {
        num += el.selectList.length;
    });
    if (props.sceneValue == 'friend' && [2, 3].includes(tabsType.value)) {
        residueNum = 1 - (num + selectLocalList.value.length);
    } else {
        residueNum = props.maxNum - (num + selectLocalList.value.length);
    }
    return residueNum;
});

const tabsDisabled = computed(() => {
    const flag =
        props.sceneValue == 'friend' && (tabs.value.some(el => el.selectList?.length) || selectLocalList.value?.length);
    return flag ? true : false;
});

/** 上传是否禁用 */
const uploadDisabled = computed(() => {
    return remainNum.value <= 0;
});

/**
 *
 */
const tableScrollBarRef = ref<any>(null);

/**
 * 不需要分组的tab类型
 */
const noGroupTabTypeList = [10, 11];

/**
 * 需要展示tabs
 */
// const showTabsList = ref<any>([]);

/**
 * 回显选中的素材与本地上传素材
 */
const selectInfo = reactive({
    materialList: [],
    localMaterialList: []
});

/**
 * 当前选中tabs的类型
 */
const tabsType = ref<any>(0);

/**
 * 当前分组数据
 */
const groupData = ref<any>([]);

/**
 * 电商素材类型
 * 0 - 商品素材
 * 1 - 页面素材
 */
const toggleType = ref<any>(0);
/**
 * 电商素材-是否只有商品素材按钮
 */
const isGoodsOnly = ref<boolean>(false);

/**
 * tab
 */
const tabs = ref<any>([
    {
        type: 0,
        groupId: 1,
        name: '文本',
        nameStr: 'text',
        total: 1,
        num: 0,
        comName: shallowRef(TextTable),
        selectList: []
    },
    {
        type: 1,
        groupId: 2,
        name: '图片',
        nameStr: 'pic',
        total: 9,
        num: 0,
        comName: shallowRef(ImageTable),
        selectList: []
    },
    {
        type: 2,
        groupId: 4,
        name: '视频',
        nameStr: 'video',
        total: 9,
        num: 0,
        comName: shallowRef(VideoTable),
        selectList: []
    },
    {
        type: 3,
        groupId: 6,
        name: '链接',
        nameStr: 'link',
        total: 9,
        num: 0,
        comName: shallowRef(LinkTable),
        selectList: []
    },
    {
        type: 4,
        groupId: 3,
        name: '音频',
        nameStr: 'audio',
        total: 9,
        num: 0,
        comName: shallowRef(AudioTable),
        selectList: []
    },
    {
        type: 5,
        groupId: 5,
        name: '文件',
        nameStr: 'file',
        total: 9,
        num: 0,
        comName: shallowRef(FileTable),
        selectList: []
    },
    {
        type: 6,
        groupId: 8,
        name: '抽奖',
        nameStr: 'luck',
        total: 9,
        num: 0,
        comName: shallowRef(LuckDrawTable),
        selectList: []
    },
    {
        type: 7,
        groupId: 99,
        name: '电商素材',
        nameStr: 'eCommerce',
        total: 9,
        num: 0,
        comName: shallowRef(ECommerceTable),
        selectList: []
    },
    {
        type: 9,
        groupId: 27,
        name: '收集表',
        nameStr: 'collect',
        total: 9,
        num: 0,
        comName: shallowRef(CollectTable),
        selectList: []
    },
    {
        type: 10,
        groupId: 15,
        name: '公众号图文',
        nameStr: 'officialAccounts',
        total: 9,
        num: 0,
        comName: shallowRef(OfficialAccountTable),
        selectList: []
    },
    {
        type: 11,
        groupId: 11,
        name: '小程序素材',
        nameStr: 'miniProgram',
        total: 9,
        num: 0,
        comName: shallowRef(MiniAppTable),
        selectList: []
    }
]);

/**
 * 本地上传的素材
 */
const selectLocalList = ref<any>([]);
/**
 * pagination分页器数据
 */
const pageInfo = reactive({
    page: 1,
    page_size: 15,
    total: 0
});

/**
 * 基础信息
 * keyword-搜索title
 * searchOfficial-公众号搜索信息
 * searchMp小程序搜索信息
 * loading-table是否loading中
 * groupLoading-组是否loading中
 * groupType-组的类型
 * group_id-当前组id
 * shopType-店铺 类型，电商素材需要
 */
const baseInfo = reactive<any>({
    keyword: '',
    searchOfficial: {
        title: '',
        id: ''
    },
    searchMp: { title: '' },
    loading: true,
    groupLoading: true,
    groupType: 1,
    group_id: 0,
    shopType: ''
});

/**
 * 每项tabs下table数据
 */
const tableData = ref<any>([]);

/**
 * tab切换类型
 */
const onTabs = async (val?: any) => {
    pageInfo.page = 1;
    pageInfo.page_size = 15;
    pageInfo.total = 0;
    baseInfo.group_id = 0;
    groupData.value = [];
    tableData.value = [];
    if (val == 7) {
        await getGroupData();
        await getTableData();
    } else {
        getGroupData();
        getTableData();
    }
};

/**
 * 切换分组
 * @param val group选中项信息
 */
const onGroupTree = (val?: any) => {
    baseInfo.group_id = val.id;
    baseInfo.shopType = val.type;
    getTableData();
};

/**
 * 获取组数据
 * 抽奖与电商素材单独接口处理
 */
const getGroupData = async () => {
    baseInfo.groupLoading = true;
    let res: any = '';
    if (tabsType.value == 6) {
        res = await luckDrawGroupListApi(app, { type: 13 });
    } else if (tabsType.value == 7) {
        res = await shopGroupListApi(app, { sub_num: 1 });
        res = res.map(item => {
            item.nums = item.sub_num || 0;
            return item;
        });
    } else {
        res = await groupListApi(app, { type: tabsGroupId.value });
    }
    const list = [
        {
            name: '全部分组',
            id: 'all',
            children: [],
            nums: 0
        }
    ];
    list[0].children = res.data || [];
    list[0].nums = res.total || 0;

    if (tabsType.value == 7) {
        groupData.value = res || [];
        baseInfo.group_id = groupData.value[0]?.id;
    } else {
        groupData.value = list;
    }
    baseInfo.groupLoading = false;
};

/**
 * 获取table数据
 */
const getTableData = async () => {
    baseInfo.loading = true;
    const { page, page_size } = pageInfo;
    const { keyword, group_id, searchOfficial, searchMp } = baseInfo;
    const params: any = {
        title: keyword,
        group_id,
        page,
        page_size
    };
    const type = tabsType.value;

    let res: any = {};
    switch (type) {
        // 文本
        case 0:
            res = await textTableApi(app, params);
            break;
        // 图片
        case 1:
            res = await imageTableApi(app, params);
            break;
        // 视频
        case 2:
            res = await videoTableApi(app, params);
            break;
        // 链接
        case 3:
            res = await linkTableApi(app, params);
            break;
        // 音频
        case 4:
            res = await audioTableApi(app, params);
            break;
        // 文件
        case 5:
            res = await fileTableApi(app, params);
            break;
        // 抽奖
        case 6:
            res = await lotteryTableApi(app, params);
            break;
        // 电商素材
        case 7:
            params.title = undefined;
            params.goods_info = keyword;
            params.shop_id = group_id;
            if (toggleType.value == 0) {
                params.goods_status = 2;
                params.stock_status = 1;
                res = await productTableApi(app, params);
            } else if (toggleType.value == 1) {
                params.page_status = 1;
                res = await pageTableApi(app, params);
            }
            break;
        // 收集表
        case 9:
            params.type = 2;
            params.title = undefined;
            params.keyword = keyword;
            res = await collectTableApi(app, params);
            break;
        // 公众号
        case 10:
            params.type = 2;
            params.publish_state = 2; // 发布状态 0-全部 1-发布中 2-发布成功 3-发布失败
            params.article_title = searchOfficial.title;
            params.official_account_id = searchOfficial.id;
            res = await officialTableApi(app, params);
            break;
        // 小程序
        case 11:
            params.title = searchMp.title;
            res = await miniTableApi(app, params);
            break;
    }

    tableData.value = res?.data || [];
    pageInfo.total = res?.total || 0;
    baseInfo.loading = false;
};

/**
 * 切换分页器-page
 * @param val
 */
const pageChange = (val: number) => {
    // tableScrollBarRef.value.setScrollTop(0);
    pageInfo.page = val;
    getTableData();
};

/**
 * 切换分页器-pagesize
 * @param val
 */
const pageSizeChange = (val: number) => {
    pageInfo.page_size = val;
    getTableData();
};

/**
 * 本地上传文件/本地创建链接
 */
const onLocalUploadFile = (val: any = {}) => {
    val.local = true;
    val.type = tabsType.value;
    selectLocalList.value.push(val);
    const list = tabs.value
        .filter((el: any) => el.selectList.length)
        .map((item: any) => {
            const { type, selectList, name, nameStr } = item;
            return { type, selectList, name, nameStr };
        });
    emit('submit', list, selectLocalList.value);
    show.value = false;
};

/**
 * 刷新页面
 */
const onRefresh = () => {
    getGroupData();
    getTableData();
};

/**
 * 关闭/取消页面
 */
const onClose = () => {
    baseInfo.group_id = 0;
    pageInfo.page = 1;
    pageInfo.page_size = 15;
    pageInfo.total = 0;
    tableData.value = [];
    tabs.value.map(el => (el.selectList = []));
    selectLocalList.value = [];
    show.value = false;
};

/**
 * 选中保存
 */
const onSave = () => {
    const list = tabs.value
        .filter((el: any) => el.selectList.length)
        .map((item: any) => {
            const { type, selectList, name, nameStr } = item;
            return { type, selectList, name, nameStr };
        });
    emit('submit', list, selectLocalList.value);
    show.value = false;
};

/**
 * 监听电商素材type类型，展示不同conName
 */
watch(toggleType, (val: any) => {
    if (val === 0) {
        tabs.value.map(el => {
            if (el.type == 7) {
                el.comName = ECommerceTable;
            }
        });
        getTableData();
    } else if (val === 1) {
        tabs.value.map(el => {
            if (el.type == 7) {
                el.comName = ECommercePageTable;
            }
        });
        getTableData();
    }
});

/**
 * 监听弹框展示
 * 初始化不同类型数据
 * 场景值是朋友圈的时候2-视频与1-链接类型只能选择一项
 */
watch(show, (val: any) => {
    if (val) {
        // tabsType.value = 0;
        if (props.showTabsList.length) {
            tabs.value = tabs.value.filter(item => props.showTabsList.includes(item.type));
        }
        if (selectInfo.materialList.length) {
            selectInfo.materialList.map((item: any) => {
                tabs.value.map((el: any) => {
                    if (item.type == el.type) {
                        el.selectList.push(item);
                    }
                });
            });
        }
        if (selectInfo.localMaterialList.length) {
            selectInfo.localMaterialList.map((item: any) => {
                selectLocalList.value.push(item);
            });
        }
        if (props.sceneValue == 'friend') {
            tabs.value.map((el: any) => {
                if (el.type == 2 || el.type == 3) {
                    el.total = 1;
                }
            });
        }

        getGroupData();
        getTableData();
    }
});

defineExpose({
    tabsType,
    selectInfo
});
</script>

<style lang="scss">
.zw-unityKit-material-lib {
    .el-dialog__body {
        padding: 0;
    }

    .el-dialog__footer {
        padding: 10px 16px;
        border-top: 1px solid #eaeaea;
    }
}
</style>
<style lang="scss" scoped>
.content {
    min-height: 500px;
}

.content-box {
    display: flex;

    .content-box-group {
        margin-bottom: 8px;
        border-right: 2px solid #eee;
    }

    .content-box-right {
        padding: 8px 16px;
        flex: 1;
    }

    .table-box {
        height: 404px;
    }
}

.tab-header {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 12px;
    position: relative;
    margin-bottom: 10px;

    &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background-color: #eee;
    }

    .base_tabs {
        width: 92%;

        :deep .el-tabs__header {
            margin: 0;

            .el-tabs__nav-wrap {
                &::after {
                    height: 0;
                }
            }
        }

        padding: 0 10px;
        box-sizing: border-box;
    }

    .tab_reset {
        width: 8%;
        text-align: center;
        white-space: nowrap;
        line-height: 38px;
        height: 38px;
        color: #ff6b00;

        &:hover {
            cursor: pointer;
            color: #f99032;
        }
    }
}

.footer-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-desc {
        flex: 1;
        text-align: left;
        margin-right: 12px;
    }

    .right-button {
        display: flex;

        .right-button-file {
            margin-right: 12px;
        }
    }
}
</style>
